package com.auxgroup.hr.front.site.co.performance;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.performance.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.commons.utils.DateUtils;
import com.auxgroup.hr.front.commons.utils.WebServiceClient;
import com.auxgroup.hr.front.commons.utils.WebServiceUtils;
import com.auxgroup.hr.front.commons.vo.BaseResponseVO;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.JobCurrPrimary;
import com.auxgroup.hr.front.dao.domain.ProcessMapRespVO;
import com.auxgroup.hr.front.dao.domain.PsCEpAppItem;
import com.auxgroup.hr.front.dao.domain.PsCEpAppItemR;
import com.auxgroup.hr.front.dao.domain.PsCEpAppRole;
import com.auxgroup.hr.front.dao.domain.PsCEpAppSec;
import com.auxgroup.hr.front.dao.domain.PsCEpDocVw;
import com.auxgroup.hr.front.dao.domain.PsCEpDocVwPrimary;
import com.auxgroup.hr.front.dao.domain.PsCEpPropsVw;
import com.auxgroup.hr.front.dao.domain.PsCWfEmpVw;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.service.performance.PerformancePlanService;
import com.auxgroup.hr.front.site.co.BaseCO;
import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.performance.AssessPersRespVO;
import com.auxgroup.hr.front.site.vo.performance.PerformancePlanRespVO;
import com.auxgroup.hr.front.site.vo.performance.PerformanceReqVO;
import com.auxgroup.hr.front.site.vo.performance.PerformanceRespVO;
import com.auxgroup.hr.front.site.vo.performance.PlanItemRespVO;
import com.auxgroup.hr.front.ws.SoapXmlBuild;

/**
 * 绩效计划审批
 * @author lv-PC
 *
 */
@RestController
@RequestMapping("${auxgroup.hr.contextPath}/plan")
public class PerformancePlanCO extends BaseCO {

	private static final Logger logger = LoggerFactory.getLogger(PerformancePlanCO.class);

	@Autowired
	public PerformancePlanService  performancePlanService;
	
	@Autowired
	public PsCWfEmpVwRepository psCWfEmpVwRepository;
	
	@Value("${ws.processService.approve.address}")
	private String processURL;
	
	@Value("${ws.processService.epPlan.soapAction}")
	private String epPlanSoapAction;
	
	/**
	 * 查询计划审批人员列表
	 * @param cTransactionNbr
	 * @param user
	 * @return
	 */
	@GetMapping("/persons")
	public BaseResponseVO getPersons(String cTransactionNbr,String queryKey,@SessionGain("user") UserDTO user){
		logger.info("performance plan getPersons param:{}",cTransactionNbr);
		if(StringUtils.isBlank(cTransactionNbr)){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		List<PsCEpDocVw> epdocs = performancePlanService.getepdocs(user.getOprId(), cTransactionNbr,queryKey,new Sort(Direction.ASC, "cEpAppStatus","treeNodeNum","seqno"));
		if(epdocs!=null&&!epdocs.isEmpty()){
			Map<String, String> per;
			List<Map<String, String>> pers = new ArrayList<Map<String,String>>();
			AssessPersRespVO respVO = new AssessPersRespVO();
			respVO.setTitle(epdocs.get(0).getText254());
			for (PsCEpDocVw epdoc : epdocs) {
				per = new HashMap<String, String>();
				per.put("name", epdoc.getName());
				per.put("emplid", epdoc.getEmplid());
				per.put("dept", epdoc.getDeptDescr());
				per.put("jobDescr", epdoc.getJobcodeDescr());
				per.put("oprid", epdoc.getOprid());
				per.put("tempName", epdoc.getDescr1());
				per.put("docid", epdoc.getcEpAppraisalId());
				per.put("version", String.valueOf(epdoc.getVersion()));
				per.put("epPhase", epdoc.getcEpPhase());
				per.put("seqnbr", epdoc.getSeqnbr()==null?"":epdoc.getSeqnbr().toString());
				per.put("flag", epdoc.getcEpAppStatus());
				pers.add(per);
			}
			respVO.setPers(pers);
			return buildRespone(respVO,false);
		}
		return buildRespone();
	}
	
	/**
	 * 计划审批人
	 * @param docid
	 * @param version
	 * @return
	 */
	@GetMapping("/planMap")
	public BaseResponseVO getProcessMap(String docid,String version,String epPhase,String evaType){
		List<List<PsCEpAppRole>> appRoles = performancePlanService.processMap(docid, version,epPhase);
		if(appRoles!=null&&!appRoles.isEmpty()){
			ProcessMapRespVO respVo;
			List<ProcessMapRespVO> respVos;
			List<List<ProcessMapRespVO>> respVolist = new ArrayList<List<ProcessMapRespVO>>();
			for (List<PsCEpAppRole> roles : appRoles) {
				respVos = new ArrayList<ProcessMapRespVO>();
				for (PsCEpAppRole role : roles) {
					respVo = new ProcessMapRespVO();
					JobCurrPrimary primary = new JobCurrPrimary();
					primary.setEmplid(role.getEmplid());
					primary.setEmplRcd(role.getEmplRcd());
					PsCWfEmpVw emp = psCWfEmpVwRepository.findOne(primary);//获取个人信息内容
					respVo.setComments(role.getComments());
					if(emp!=null){
						respVo.setEmplName(emp.getNameDisplay());//姓名
					}
					if("A".equals(evaType)){
						respVo.setScore(role.getcEpScoreRevised()==null?"":role.getcEpScoreRevised().toString());
					}else{
						respVo.setScore(role.getcEpGradeRevised()==null?"":role.getcEpGradeRevised().toString());
					}
					respVo.setLastupddttm(DateUtils.format(role.getLastupddttm(), DateUtils.FORMAT_DEFAULT));
					respVo.setcStepStatus(role.getcEpAppStatus());
					respVo.setDescr(role.getcEpRolename());
					respVos.add(respVo);
				}
				respVolist.add(respVos);
			}
			return buildRespone(respVolist,false);
		}
		return buildRespone();
	}
	
	/**
	 * 查询绩效信息
	 * @return
	 */
	@GetMapping("/performance")
	public BaseResponseVO getPerformanceInfo(PerformanceReqVO reqVo, @SessionGain("user") UserDTO user){
		//获取绩效计划审批头表
		PsCEpDocVwPrimary primary = new PsCEpDocVwPrimary();
		primary.setcEpAppraisalId(reqVo.getDocid());
		primary.setcTransactionNbr(reqVo.getcTransactionNbr());
		primary.setcWfType(reqVo.getWfType());
		primary.setOprid(user.getOprId());
		primary.setVersion(new BigDecimal(reqVo.getVersion()));
		primary.setSeqnbr(new BigDecimal(reqVo.getSeqnbr()));
		primary.setcEpPhase(reqVo.getEpPhase());
		PsCEpDocVw docVw = performancePlanService.getepdoc(primary);
		if(docVw==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		PerformanceRespVO respVo = new PerformanceRespVO();
		respVo.setDept(docVw.getDeptDescr());
		respVo.setEmplid(docVw.getEmplid());
		respVo.setJodDescr(docVw.getJobcodeDescr());
		respVo.setName(docVw.getName());
		respVo.setTempName(docVw.getDescr1());
		respVo.setEvaType(docVw.getcEvaType());
		//构建评论信息
		buildScore(respVo,docVw,user.getEmplId());
		List<PsCEpAppSec> secs = performancePlanService.getEpAppSecs(docVw);
		if(secs==null||secs.isEmpty()){
			return buildRespone(Collections.EMPTY_LIST,false);
		}
		//构建区段信息
		List<PerformancePlanRespVO> respVos =buildRespVos(secs,docVw);
		respVo.setPerfors(respVos);
		return buildRespone(respVo,false);
	}
	
	private void buildScore(PerformanceRespVO respVo,PsCEpDocVw docVw,String emplid){
		PsCEpAppRole role = performancePlanService.getEpAppRole(docVw, emplid);
		if(role!=null){
			respVo.setComments(role.getComments());
			if("A".equals(docVw.getcEvaType())){
				respVo.setScore(role.getcEpScore()==null||role.getcEpScore().compareTo(BigDecimal.ZERO)==0?"":role.getcEpScore().toString());
				respVo.setRevisedScore(role.getcEpScoreRevised()==null||role.getcEpScoreRevised().compareTo(BigDecimal.ZERO)==0?"":role.getcEpScoreRevised().toString());
			}else{
				respVo.setScore(role.getcEpGrade()==null?"":role.getcEpGrade().toString());
				respVo.setRevisedScore(role.getcEpGradeRevised()==null?"":role.getcEpGradeRevised().toString());
			}
		}
	}
	
	
	
	private List<PerformancePlanRespVO> buildRespVos(List<PsCEpAppSec> secs,PsCEpDocVw docVw){
		List<PerformancePlanRespVO> respVos = new ArrayList<PerformancePlanRespVO>();
		PerformancePlanRespVO respVo;
		List<PlanItemRespVO> itemRespVos;
		for (PsCEpAppSec sec : secs) {
			respVo = new PerformancePlanRespVO();
			respVo.setSectionDesc(sec.getcEpSectionName());
			respVo.setSectionType(sec.getcEpSectionType());
			respVo.setSectionId(sec.getcEpSectionId().toString());
			if("A".equals(sec.getcEpSectionType())){
				respVo.setSectionWeight("权重："+sec.getEpWeight()+"%");
			}else{
				respVo.setSectionWeight(" ");
			}
			List<PsCEpAppItem> items = performancePlanService.getEpAppItems(docVw, sec.getcEpSectionId());
			PlanItemRespVO itemRespVo;
			itemRespVos = new ArrayList<PlanItemRespVO>();
			if(items!=null){
				for (PsCEpAppItem item : items) {
					itemRespVo = new PlanItemRespVO();
					itemRespVo.setItemDesc(item.getDescr());
					if("A".equals(sec.getcEpSectionType())){
						itemRespVo.setItemWeight(item.getEpWeight()+"%");
					}else{
						itemRespVo.setItemWeight(" ");
					}
					itemRespVo.setItemOther(performancePlanService.getItemOhterDescr(item));
					itemRespVo.setCatType(item.getcEpCatType());
					itemRespVo.setItemId(item.getcEpCatItemId());
					itemRespVo.setSectionId(sec.getcEpSectionId().toString());
					PsCEpAppItemR itemR = performancePlanService.getEpAppItemR(docVw, item.getcEpSectionId(), item.getcEpCatType(), item.getcEpCatItemId());
					if(itemR!=null){
						itemRespVo.setComment(itemR.getComments());
						itemRespVo.setScore(performancePlanService.getCommentScore(docVw.getcEvaType(), itemR, sec.getcEpSectionType()));
					}
					itemRespVos.add(itemRespVo);
				}
			}
			respVo.setItems(itemRespVos);
			respVos.add(respVo);
		}
		return respVos;
	}
	
	
	
	
	@GetMapping("/itemDetail")
	public BaseResponseVO itemDetail(PerformanceReqVO reqVo,@SessionGain("user") UserDTO user){
		//获取绩效计划审批头表
		PsCEpDocVwPrimary primary = new PsCEpDocVwPrimary();
		primary.setcEpAppraisalId(reqVo.getDocid());
		primary.setcTransactionNbr(reqVo.getcTransactionNbr());
		primary.setcWfType(WfTypeEnum.WF_STYPE_EPPL.getType());
		primary.setOprid(user.getOprId());
		primary.setVersion(new BigDecimal(reqVo.getVersion()));
		primary.setcEpPhase(reqVo.getEpPhase());
		primary.setSeqnbr(new BigDecimal(reqVo.getSeqnbr()));
		PsCEpDocVw docVw = performancePlanService.getepdoc(primary);
		if(docVw==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		PsCEpAppItem item = performancePlanService.getEpAppItem(docVw, new BigDecimal(reqVo.getSectionId()), reqVo.getCatType(), reqVo.getItemId());
		if(item==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		List<PsCEpPropsVw> props = performancePlanService.getItemProps(item.getcEpCatType());
		if(props==null||props.isEmpty()){
			return buildRespone(Collections.EMPTY_LIST);
		}
		List<Map<String, Object>> respList = performancePlanService.buildRespItemDetail(props, item);
		return buildRespone(respList,false);
	}
	
	/**
	 * 绩效计划审批
	 * @param reqVo
	 * @param user
	 * @return
	 */
	@PostMapping("/planApprove")
	public BaseResponseVO planApprove(PerformanceReqVO reqVo,@SessionGain("user") UserDTO user){
		PsCEpDocVwPrimary primary = new PsCEpDocVwPrimary();
		primary.setcEpAppraisalId(reqVo.getDocid());
		primary.setcTransactionNbr(reqVo.getcTransactionNbr());
		primary.setcWfType(WfTypeEnum.WF_STYPE_EPPL.getType());
		primary.setOprid(user.getOprId());
		primary.setVersion(new BigDecimal(reqVo.getVersion()));
		primary.setcEpPhase(reqVo.getEpPhase());
		primary.setSeqnbr(new BigDecimal(reqVo.getSeqnbr()));
		PsCEpDocVw docVw = performancePlanService.getepdoc(primary);
		if(docVw==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		StringBuilder soapXml = new StringBuilder();
		SoapXmlBuild.buildEpPlan(soapXml, reqVo.getDocid(), reqVo.getVersion(), docVw.getSeqnbr().toString(), docVw.getOprid(),
				user.getEmplId(), reqVo.getAction(), reqVo.getComments());
		String responXml = WebServiceClient.doPostSoap(processURL, soapXml.toString(), epPlanSoapAction);
		Map<String, String> result = WebServiceUtils.handleRespXml(responXml, "C_EP_APP_RSP");
		if(result!=null){
			if(result.containsKey("RETURN_CODE")&&"SUCCESS".equals(result.get("RETURN_CODE"))){
				return buildRespone(BaseRetCode.CODE_SUCCESS);
			}else{
				return buildRespone(BaseRetCode.CODE_ERROR_SYS.getRetCode(),result.get("RETURN_DESCR"));
			}
		}
		return buildRespone(BaseRetCode.CODE_ERROR_SYS.getRetCode(),"流程审批失败请稍后再试");
	}
	
}
